package com.chushouya.manager.service.common.impl;

import com.chushouya.manager.dao.entity.PartnerRuleEntity;
import com.chushouya.manager.dao.repository.PartnerRulesRepository;
import com.chushouya.manager.dto.common.PartnerRuleItemDTO;
import com.chushouya.manager.service.common.PartnerRuleService;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PartnerRuleServiceImpl implements PartnerRuleService {
    
    @Resource
    private PartnerRulesRepository partnerRulesRepository;
    
    @Override
    public PartnerRuleEntity getPartnerRuleByPartnerId(Long partnerId) {
        if (partnerId == null) {
            log.warn("合作商ID为空，无法获取规则");
            return null;
        }
        
        try {
            PartnerRuleEntity partnerRule = partnerRulesRepository.selectByPartnerId(partnerId);
            log.debug("获取合作商规则: partnerId={}, rule={}", partnerId, partnerRule != null ? "存在" : "不存在");
            return partnerRule;
        } catch (Exception e) {
            log.error("获取合作商规则失败: partnerId={}, error={}", partnerId, e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    public List<PartnerRuleItemDTO> getPartnerRuleItems(Long partnerId) {
        PartnerRuleEntity partnerRule = getPartnerRuleByPartnerId(partnerId);
        if (partnerRule == null || Strings.isEmpty(partnerRule.getRules())) {
            log.debug("合作商规则为空: partnerId={}", partnerId);
            return new ArrayList<>();
        }
        
        try {
            List<PartnerRuleItemDTO> ruleItems = Jsons.parseArray(partnerRule.getRules(), PartnerRuleItemDTO.class);
            log.debug("解析合作商规则成功: partnerId={}, ruleCount={}", partnerId, ruleItems.size());
            return ruleItems;
        } catch (Exception e) {
            log.error("解析合作商规则失败: partnerId={}, rules={}, error={}", partnerId, partnerRule.getRules(), e.getMessage(), e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public BigDecimal calculatePartnerMarkup(Long partnerId, BigDecimal price) {
        if (partnerId == null || price == null || price.compareTo(BigDecimal.ZERO) <= 0) {
            log.debug("参数无效，无法计算合作商加价: partnerId={}, price={}", partnerId, price);
            return BigDecimal.ZERO;
        }
        
        List<PartnerRuleItemDTO> ruleItems = getPartnerRuleItems(partnerId);
        if (ruleItems.isEmpty()) {
            log.debug("合作商规则为空，无加价: partnerId={}", partnerId);
            return BigDecimal.ZERO;
        }
        
        // 查找匹配的价格区间
        for (PartnerRuleItemDTO ruleItem : ruleItems) {
            if (isPriceInRange(price, ruleItem)) {
                BigDecimal markup = calculateMarkupByRule(price, ruleItem);
                log.info("合作商加价计算: partnerId={}, price={}, range=[{}-{}], markup={}", 
                        partnerId, price, ruleItem.getBegin(), ruleItem.getEnd(), markup);
                return markup;
            }
        }
        
        log.debug("未找到匹配的价格区间: partnerId={}, price={}", partnerId, price);
        return BigDecimal.ZERO;
    }
    
    /**
     * 判断价格是否在规则区间内
     */
    private boolean isPriceInRange(BigDecimal price, PartnerRuleItemDTO ruleItem) {
        BigDecimal begin = ruleItem.getBegin();
        BigDecimal end = ruleItem.getEnd();
        
        if (begin == null || end == null) {
            return false;
        }
        
        return price.compareTo(begin) >= 0 && price.compareTo(end) <= 0;
    }
    
    /**
     * 根据规则计算加价金额
     */
    private BigDecimal calculateMarkupByRule(BigDecimal price, PartnerRuleItemDTO ruleItem) {
        String value = ruleItem.getValue();
        Integer type = ruleItem.getType();
        
        if (Strings.isEmpty(value) || type == null) {
            return BigDecimal.ZERO;
        }
        
        try {
            BigDecimal markupValue = new BigDecimal(value);
            
            if (type == 1) {
                // 固定金额
                return markupValue;
            } else if (type == 2) {
                // 百分比
                return price.multiply(markupValue).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
            } else {
                log.warn("未知的加价类型: type={}", type);
                return BigDecimal.ZERO;
            }
        } catch (NumberFormatException e) {
            log.error("解析加价值失败: value={}, error={}", value, e.getMessage());
            return BigDecimal.ZERO;
        }
    }
}
